package org.ipti.br.tag.pdf;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.ipti.br.tag.entity.Human;
import org.ipti.br.tag.entity.Unity;
import org.ipti.br.tag.entity.Actor;
import org.ipti.br.tag.entity.enums.PersonageType;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import javax.ejb.Stateless;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.ipti.br.tag.bean.SessionBean;
import org.ipti.br.tag.bean.dataManipulation.Month;
import org.ipti.br.tag.bo.HumanBO;
import org.ipti.br.tag.util.CalendarUtil;

@Stateless
public class DeclarationPDF extends AbstractPdf implements Serializable {

    @Inject 
    private SessionBean sessionBean;
    @Inject HumanBO humanBO;
    private Unity unity;
    private Unity loggedUnity;

    public void run(Unity loggedUnity, List<int[]> cargaHoraria, List<long[]> numberOfFaults, List<int[]> frequency, List<Actor> actorList)
            throws FileNotFoundException, DocumentException, IOException {


        
        this.loggedUnity = loggedUnity;

        this.init("Declaração do bolsa família");

        addMetaData();
        addTitle();
        addHead();
        int count = 0;
        for (Actor actor : actorList){
            this.unity = actor.getUnity();
            addBody(actor, cargaHoraria.get(count), numberOfFaults.get(count), frequency.get(count));
            count++;
        }

        close();
        export();
    }

    private void addMetaData() {
        this.getDocument().addTitle("Declaração (Bolsa Familia)");
        this.getDocument().addSubject("");
        this.getDocument().addKeywords("Declaração, Bolsa Familia, TAG, IPTI");
        this.getDocument().addAuthor("Instituto de Pesquisa em Tecnologia e Inovação - IPTI");
        this.getDocument().addCreator("Tecnologia de Apoio a Gestão - TAG");
    }

    private void addTitle() throws DocumentException, BadElementException, MalformedURLException, IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        Image image;
        image = Image.getInstance(externalContext.getRealPath("SLDI.jpg"));
        image.scaleAbsoluteWidth(140);
        image.scaleAbsoluteHeight(65);
        image.setAlignment(Element.ALIGN_CENTER);
        image.setSpacingAfter(40);
        this.getDocument().add(image);

        Paragraph preface = new Paragraph();
        Paragraph title = new Paragraph("Prefeitura de Santa Luzia do Itanhi", super.getCatFont());
        title.setAlignment(Paragraph.ALIGN_CENTER);
        preface.add(title);

        Paragraph subTitle = new Paragraph("DECLARAÇÃO", super.getSubFont());
        subTitle.setAlignment(Paragraph.ALIGN_CENTER);
        preface.add(subTitle);

        addEmptyLine(preface, 1);
        this.getDocument().add(preface);
    }

    public void addHead() throws DocumentException {
        Paragraph head = new Paragraph();
        Paragraph field = new Paragraph("Escola: ", super.getSubFont());
        field.add(new Phrase(loggedUnity.getName(), super.getSubFont()));
        head.add(field);

        field = new Paragraph();
        head.add(field);

        addEmptyLine(head, 1);

        head.setFont(super.getTextF());
        this.getDocument().add(head);
    }
      
    public void addBody(Actor a, int[] schoolDays, long[] numberOfFaults, int[] frequency  ) throws DocumentException {
        
        Human student = (Human) a.getPerson();
        
        float widths[] = {0.75f,0.25f};
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(100);
        PdfPCell cellInfo = new PdfPCell(
                new Paragraph(student.getName().toUpperCase() + 
                              "\nNascimento: " + CalendarUtil.getFormatedText(student.getBirthday()) +
                              "\nNIS: " + (!student.getAdditionalInfos().isEmpty() && 
                                            student.getAdditionalInfos().get(0).getAdditionalInfoType().getAcronym().equals("NIS") ? 
                                            student.getAdditionalInfos().get(0).getValue() : "Não registrado") +
                              "\nSérie: "+ a.getUnity().getName()+" - " + a.getUnity().getActivated().get(Calendar.YEAR) , super.getFontTextNORMAL())
                );
                
    
        float widthsFerquency[] = {0.50f,0.50f};
        PdfPTable tableFrequency = new PdfPTable(widthsFerquency);
        tableFrequency.setWidthPercentage(100);
        
        int first   = (Calendar.getInstance().get(Calendar.MONTH));
        int second  = (Calendar.getInstance().get(Calendar.MONTH) -1) == -1 ? 11 : (Calendar.getInstance().get(Calendar.MONTH) -1);
        int third   = (Calendar.getInstance().get(Calendar.MONTH) -2) == -1 ? 11 : ((Calendar.getInstance().get(Calendar.MONTH) -2) == -2 ? 10 : (Calendar.getInstance().get(Calendar.MONTH) -2));
        PdfPCell cellFrequencyHead = new PdfPCell(new Paragraph("Mês", super.getFontTextBold()));
        PdfPCell cellFrequencyValue = new PdfPCell(new Paragraph("Frequência", super.getFontTextBold()));
        
        cellFrequencyHead.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellFrequencyValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        
        tableFrequency.addCell(cellFrequencyHead);
        tableFrequency.addCell(cellFrequencyValue);
        
        String frequencia = "";
        if (frequency[first] == -1){
            frequencia = "N/A";
        }else{
            frequencia = frequency[first]+"%";
        }
        cellFrequencyHead = new PdfPCell(new Paragraph(Month.getMonth(first)+":", super.getFontTextNORMAL()));
        cellFrequencyValue = new PdfPCell(new Paragraph(frequencia, super.getFontTextNORMAL()));
        
        cellFrequencyHead.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        cellFrequencyValue.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        
        tableFrequency.addCell(cellFrequencyHead);
        tableFrequency.addCell(cellFrequencyValue);
        
        frequencia = "";
        if (frequency[second] == -1){
            frequencia = "N/A";
        }else{
            frequencia = frequency[second]+"%";
        }
        cellFrequencyHead = new PdfPCell(new Paragraph(Month.getMonth(second)+":", super.getFontTextNORMAL()));
        cellFrequencyValue = new PdfPCell(new Paragraph(frequencia, super.getFontTextNORMAL()));
        tableFrequency.addCell(cellFrequencyHead);
        tableFrequency.addCell(cellFrequencyValue);
        
        frequencia = "";
        if (frequency[third] == -1){
            frequencia = "N/A";
        }else{
            frequencia = frequency[third]+"%";
        }
        cellFrequencyHead = new PdfPCell(new Paragraph(Month.getMonth(third)+":", super.getFontTextNORMAL()));
        cellFrequencyValue = new PdfPCell(new Paragraph(frequencia, super.getFontTextNORMAL()));
        tableFrequency.addCell(cellFrequencyHead);
        tableFrequency.addCell(cellFrequencyValue); 
        
        PdfPCell cellFrequency = new PdfPCell(tableFrequency);
        
        cellInfo.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        cellFrequency.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        table.addCell(cellInfo);
        table.addCell(cellFrequency);
            
        this.getDocument().add(table);
    }

    public void addFrequency(int[] schoolDays, long[] numberOfFaults, int[] frequency) throws DocumentException {

        Paragraph schoolFrequency = new Paragraph("FREQUÊNCIA ESCOLAR", super.getSubFont());
        schoolFrequency.setAlignment(Paragraph.ALIGN_CENTER);

        addEmptyLine(schoolFrequency, 1);

        PdfPTable table = new PdfPTable(13);
        table.setWidthPercentage(100);
        PdfPCell cellMonth = new PdfPCell(new Paragraph("MÊS", super.getFontTextBold()));
        PdfPCell cellJan = new PdfPCell(new Paragraph("JAN", super.getFontTextBold()));
        PdfPCell cellFeb = new PdfPCell(new Paragraph("FEV", super.getFontTextBold()));
        PdfPCell cellMar = new PdfPCell(new Paragraph("MAR", super.getFontTextBold()));
        PdfPCell cellApr = new PdfPCell(new Paragraph("ABR", super.getFontTextBold()));
        PdfPCell cellMay = new PdfPCell(new Paragraph("MAI", super.getFontTextBold()));
        PdfPCell cellJun = new PdfPCell(new Paragraph("JUN", super.getFontTextBold()));
        PdfPCell cellJul = new PdfPCell(new Paragraph("JUL", super.getFontTextBold()));
        PdfPCell cellAug = new PdfPCell(new Paragraph("AGO", super.getFontTextBold()));
        PdfPCell cellSep = new PdfPCell(new Paragraph("SET", super.getFontTextBold()));
        PdfPCell cellOct = new PdfPCell(new Paragraph("OUT", super.getFontTextBold()));
        PdfPCell cellNov = new PdfPCell(new Paragraph("NOV", super.getFontTextBold()));
        PdfPCell cellDec = new PdfPCell(new Paragraph("DEZ", super.getFontTextBold()));
        PdfPCell cell = new PdfPCell();


        cellMonth.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellJan.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellFeb.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellMar.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellApr.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellMay.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellJun.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellJul.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellAug.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellSep.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellOct.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellNov.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellDec.setHorizontalAlignment(Element.ALIGN_CENTER);


        table.addCell(cellMonth);
        table.addCell(cellJan);
        table.addCell(cellFeb);
        table.addCell(cellMar);
        table.addCell(cellApr);
        table.addCell(cellMay);
        table.addCell(cellJun);
        table.addCell(cellJul);
        table.addCell(cellAug);
        table.addCell(cellSep);
        table.addCell(cellOct);
        table.addCell(cellNov);
        table.addCell(cellDec);


        cell.addElement(new Paragraph("D.L.", super.getFontTextBold()));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        for (int i = 0; i < 12; i++) {
            cell = new PdfPCell();
            cell.addElement(new Paragraph("" + schoolDays[i], super.getFontTextNORMAL()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
        }

        cell = new PdfPCell();

        cell.addElement(new Paragraph("N°F.", super.getFontTextBold()));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        for (int i = 0; i < 12; i++) {
            cell = new PdfPCell();
            cell.addElement(new Paragraph(""+ numberOfFaults[i], super.getFontTextNORMAL()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
        }

        cell = new PdfPCell();

        cell.addElement(new Paragraph("FREQ.", super.getFontTextBold()));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        for (int i = 0; i < 12; i++) {
            cell = new PdfPCell();
            cell.addElement(new Paragraph(frequency[i] + "%", super.getFontTextNORMAL()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
        }

        cell = new PdfPCell();

        this.getDocument().add(schoolFrequency);
        this.getDocument().add(table);

        Paragraph label1 = new ListItem("Legenda: D.L. - Dias Letivos", super.getTextF());
        Paragraph label2 = new ListItem("N°F. Número de Faltas", super.getTextF());
        Paragraph label3 = new ListItem("FREQ - Frequência", super.getTextF());

        addEmptyLine(label3, 1);

        Paragraph date = new ListItem("Santa Luzia do Itanhi - SE, _____ de ________________ de 20____ ", super.getFontTextNORMAL());
        Paragraph signature = new ListItem("___________________________");
        Paragraph signature2 = new ListItem("Diretor da Escola", super.getFontTextNORMAL());

        date.setAlignment(Paragraph.ALIGN_CENTER);
        signature.setAlignment(Paragraph.ALIGN_CENTER);
        signature2.setAlignment(Paragraph.ALIGN_CENTER);

        this.getDocument().add(label1);
        this.getDocument().add(label2);
        this.getDocument().add(label3);
        this.getDocument().add(date);
        this.getDocument().add(signature);
        this.getDocument().add(signature2);
    }
}
